<?php
namespace Wx\Controller;
use Common\Controller\HomebaseController;
require_once './plugins/WxPay/WxPay.JsApiPay.php';

class WxLoginController extends HomebaseController {

    // 开放平台
    private $appid              = 'wxb70eb6c4cdc9b252';
    private $appSecret          = 'b25ba507a90cd11306c09a9db78fba6e';

    // 公众号
    private $appid1             = 'wx49bdd7dc46906d38';
    private $appSecret1         = 'cd98281bfa405a8a70fb80f36585bb33';

    // 小程序
    private $minpro_appid       = "wx19ae88f77bba2fe5";
    private $minpro_appSecret   = "b99d68077dfe6b6abe9b1082864ac19e";


    // 静默获取微信公众号用户信息
    public function get_wx_user_base_info()
    {
        $tools      = new \JsApiPay();
        $open_id    = $tools->GetOpenid();
        $user       = sp_get_current_user();
        if (!$user['oa_openid']) {
            M('users')->where(['id' => $user['id']])->save(['oa_openid' => $open_id]);
            $user['oa_openid'] = $open_id;
            sp_update_current_user($user);
        }
        $redirect = I('get.redirect', '');
        if (empty($redirect)) {
            $redirect = '/';
        } else {
            $redirect = base64_decode($redirect);
        }
        $this->redirect($redirect);
    }

    // 微信app内登录 2 接受code  通过code换取网页授权access_token -- 公众平台
    public function get_wx_login_access_token()
    {
        $code    = I('code');
        $user_id = I('state');
        $url     = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        $url     .= 'appid=' . $this->appid1;
        $url     .= '&secret=' . $this->appSecret1;
        $url     .= '&code=' . $code;
        $url     .= '&grant_type=authorization_code';

        $re = curl_requestion($url);
        if ($re['status']) {
            $data = json_decode($re['data'], true);

            // 获取用户信息
            $url    = 'https://api.weixin.qq.com/sns/userinfo?';
            $url   .= 'access_token=' . $data['access_token'];
            $url   .= '&openid=' . $data['openid'];
            $url   .= '&lang=zh_CN';

            $re = curl_requestion($url);
            if ($re['status']) {
                $data           = json_decode($re['data'], true);
                $unionid        = $data['unionid'];
                $data['avatar'] = $this->_set_weixin_user_avatar($unionid, $data['headimgurl']);
                if ($user_id) {
                    $this->_old_user_bind_weixin($user_id, ['oa_openid' => $data['openid']], $unionid);
                } else {
                    $data['o_from'] = 'oa';
                    $this->_login($data);
                }
            }
        }
    }

    // PC端微信登录二维码的页面
    public function login_qrcode()
    {
        if (sp_is_user_login()) {
            $this->assign('user_id', sp_get_current_userid());
        }
        $this->display();
    }

    // 用户扫描pc端登录二维码回调地址 -- 开放平台
    public function wx_login_callback()
    {
        $code = I('code');
        if ($code) { // 用户授权

            // 获取access_token
            $url  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=";
            $url .= $this->appid;
            $url .= "&secret=" . $this->appSecret;
            $url .= "&code=" . $code;
            $url .= '&grant_type=authorization_code';

            $re = curl_requestion($url);
            if ($re['status']) {
                $data = json_decode($re['data'], true);

                // 老用户绑定微信
                $user_id = I('state');
                if ($user_id) {
                    $this->_old_user_bind_weixin($user_id, ['op_openid' => $data['openid']], $data['unionid']);
                } else {
                    $data = $this->_get_wx_user_info($data);
                    $data['o_from'] = 'op';
                    $this->_login($data);
                }
            }
        }
    }

    // 新的微信用户
    public function new_weixin_user()
    {
        $unionid    = I('unionid');
        $avatar     = I('avatar');
        $nickname   = I('nickname');
        $sex        = I('sex');
        $oa_openid  = I('oa_openid');
        $op_openid  = I('op_openid');
        $mn_openid  = I('mn_openid');
        $user_model = M('users');

        if (empty($unionid)) {
            $this->error('登录信息过期，请重新登录');exit;
        }

        $user_info  = array(
            'user_login'      => $nickname,
            'user_email'      => '',
            'mobile'          => '',
            'user_nicename'   => $nickname,
            'user_pass'       => '',
            'last_login_ip'   => get_client_ip(0, true),
            'create_time'     => date("Y-m-d H:i:s"),
            'last_login_time' => date("Y-m-d H:i:s"),
            'user_status'     => 1,
            "user_type"       => 2,//会员
            'unionid'         => $unionid,
            'sex'             => $sex == 2 ? 0 : 1,
            'avatar'          => $avatar ?: '',
            'oa_openid'       => $oa_openid,
            'op_openid'       => $op_openid,
            'mn_openid'       => $mn_openid,
        );

        $result = $user_model->add($user_info);
        if ($result) {
            //注册成功页面跳转
            $user_info['id'] = $result;
            sp_update_current_user($user_info);
            $this->assign($user_info);

            $session_login_http_referer = session('login_http_referer');
            $redirect                   = empty($session_login_http_referer) ? __ROOT__ . "/" : $session_login_http_referer;
            session('login_http_referer', '');

            $this->success('正在登录', $redirect);
        } else {
            $this->error('系统繁忙，请稍后登录');
        }
    }

    // 小程序初始化登录，根据code获取用户登录信息
    public function mini_login()
    {
        $code       = I('code', '');
        $avatar     = I('avatar', '');
        $nickname   = I('nickname', '');
        $sex        = I('sex', 1);
        if ($code) {
            $url    = "https://api.weixin.qq.com/sns/jscode2session?appid=";
            $url    .= $this->minpro_appid;
            $url    .= "&secret=" . $this->minpro_appSecret;
            $url    .= "&js_code=" . $code;
            $url    .= "&grant_type=authorization_code";

            $re = curl_requestion($url);
            if ($re['status']) {
                $data = json_decode($re['data'], true);
                if ($data['errcode'] == 0) {
                    $data['avatar']     = urldecode($avatar);
                    $data['nickname']   = $nickname;
                    $data['o_from']     = 'mn';
                    $data['sex']        = $sex;
                    $this->_login($data);
                } else {
                    writeFile("=====  mini_login  ======");
                    writeFile($data['errmsg']);
                    $this->redirect(__ROOT__ . "/");
                }
            } else {
                writeFile("=====  mini_login  ======");
                writeFile("获取用户openid失败");
                $this->redirect(__ROOT__ . "/");
            }
        } else {
            writeFile("=====  mini_login  ======");
            writeFile("code参数错误");
            $this->redirect(__ROOT__ . "/");
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private function _login($data)
    {
        $unionid    = $data['unionid'];
        $user_model = M('users');
        $user_info  = $user_model->where(['unionid' => $unionid])->find();

        // 会跳地址
        $session_login_http_referer = session('login_http_referer');
        $redirect                   = empty($session_login_http_referer) ? __ROOT__ . "/" : $session_login_http_referer;
        session('login_http_referer', '');

        if ($user_info) {
            // 老用户
            $update = array(
                'last_login_time' => date("Y-m-d H:i:s"),
                'last_login_ip'   => get_client_ip(0, true),
                'avatar'          => $data['avatar'],
            );
            if ($data['o_from'] == 'oa') {
                $update['oa_openid'] = $data['openid'];
            } elseif ($data['o_from'] == 'op') {
                $update['op_openid'] = $data['openid'];
            } elseif ($data['o_from'] == 'mn') {
                $update['mn_openid'] = $data['openid'];
            }
            $user_model->where(['id' => $user_info['id']])->save($update);
            $user_info = $user_model->where(['id' => $user_info['id']])->find();
            sp_update_current_user($user_info);
            $this->assign($user_info);

            $this->success('登录成功', $redirect);
        } else {
            // 新用户
            if ($data['o_from'] == 'oa') {
                $data['oa_openid'] = $data['openid'];
            } elseif ($data['o_from'] == 'op') {
                $data['op_openid'] = $data['openid'];
            } elseif ($data['o_from'] == 'mn') {
                $data['mn_openid'] = $data['openid'];
            }
            $this->assign('redirect_url', $redirect);
            $this->assign('wx_user_info', $data);
            $this->assign('new_weixin_user', 1);
            $this->display('User@:login');
        }
    }

    // 获取微信用户信息
    private function _get_wx_user_info($data)
    {
        $url     = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'];
        $re      = curl_requestion($url);
        $info    = array();
        if ($re['status']) {
            $info           = json_decode($re['data'], true);
            $unionid        = $info['unionid'];
            $info['avatar'] = $this->_set_weixin_user_avatar($unionid, $info['headimgurl']);
        }
        return $info;
    }

    // 老用户绑定微信
    public function _old_user_bind_weixin($user_id, $openid_array = array(), $unionid = '')
    {
        $user_model = M('users');
        $user_info  = $user_model->where(['id' => $user_id])->find();
        if ($user_info) {

            // 该账户已绑定过微信
            if ($user_info['unionid']) {
                $this->error('该账户已绑定过微信', U('User/Profile/edit'));
            }

            // 微信号之前被绑定过，或之前登录过
            $weixin_user = $user_model->where(['unionid' => $unionid])->find();
            if ($weixin_user) {
                $this->error('该微信已被使用', U('User/Profile/edit'));
            }

            // 老用户
            $data = array(
                'last_login_time' => date("Y-m-d H:i:s"),
                'last_login_ip'   => get_client_ip(0, true),
                'unionid'         => $unionid,
            );
            $data = array_merge($data, $openid_array);
            $user_model->where(['id' => $user_id])->save($data);
            $user_info = $user_model->where(['id' => $user_info['id']])->find();
            sp_update_current_user($user_info);

            $session_login_http_referer = session('login_http_referer');
            $redirect                   = empty($session_login_http_referer) ? U('User/Profile/edit') : $session_login_http_referer;
            session('login_http_referer', '');

            $this->success('绑定成功', $redirect);
        } else {
            $this->error('账号异常', U('User/Profile/edit'));
        }
    }

    public function _set_weixin_user_avatar($unionid, $headimgUrl)
    {
        $path   = 'avatar/' . $unionid . '.jpg';
        $dir    = './data/upload/' . $path;
        $change = false;
        if (file_exists($dir)) {
            $c_time = filemtime($dir);
            if ((time() - $c_time) > (30 * 24 * 60 * 60)) {
                // 每月更新一次
                $change = true;
            }
        } else {
            $change = true;
        }

        // 头像本地存储
        if ($change) {
            $avatar = file_get_contents($headimgUrl);
            if ($avatar) {
                file_put_contents($dir, $avatar);
                return $path;
            } else {
                return $headimgUrl;
            }
        } else {
            return $path;
        }
    }
}
